import { CSSRuleObject, styled } from "styledfc";
import bg from "/tabbar-bg.svg";
import { RouterItem } from "../App";
import { FlexCss, PositionCss } from "../utils/styledfc";
import { useEffect, useState } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { Toast } from "react-vant";

type TabbarProps = React.PropsWithChildren<{
    routerList: RouterItem[];
}>;
const Tabbar = (props: TabbarProps) => {
    const [active, setActive] = useState(0);
    const navigate = useNavigate();
    const location = useLocation();
    const pathTo = (index: number, item: RouterItem) => {
        if (!localStorage.getItem("pet-userInfo") && item.path === "/col") {
            Toast.info("请先登录");
            return;
        }
        setActive(index);
        navigate(item.path);
    };
    const { routerList } = props;

    useEffect(() => {
        let index = routerList.findIndex((item) => item.path === location.pathname);
        setActive(index);
    });
    return (
        <div className={tabbar.className} style={{ display: active === -1 ? "none" : "block" }}>
            <ul>
                {routerList.map((item, index) => (
                    <li onClick={() => pathTo(index, item)} key={item.icon} className={index === active ? "active" : ""}>
                        <img src={index === active ? item.iconActive : item.icon} alt="" />
                    </li>
                ))}
            </ul>
        </div>
    );
};
const tabbar = styled<CSSRuleObject>({
    background: `url(${bg}) center top/cover no-repeat`,
    ...(FlexCss("center", "center") as CSSRuleObject),
    ...(PositionCss("fixed", { bottom: "0px", left: "0px" }) as CSSRuleObject),
    width: "100%",
    height: "77rem",
    "> ul": {
        ...(FlexCss("flex-end", "space-around") as CSSRuleObject),
        height: "60rem",
        width: "98%",
        marginBottom: "8rem",
        "> li": {
            height: "30rem",
            width: "30rem",
            borderRadius: "10rem",
            transition: ".3s",
            ...(FlexCss("center", "center") as CSSRuleObject),
            "> img": {
                height: "18rem",
                width: "18rem",
            },
            ":where(.active)": {
                backgroundColor: "#A1B275",
            },
        },
    },
});
export default Tabbar;
